//
//  JYInfoInputView.m
//  MYCCBRegisterSubAccount
//
//  Created by 应明顺 on 2018/7/5.
//  Copyright © 2018年 JackYing. All rights reserved.
//


#import "JYBaseInputView.h"

@interface JYBaseInputView () {
    UITextField *_textField;
    NSMapTable <NSString *, id <JYAdaptorInputViewDelegate>> *_delegateList;
    NSLock *lock;
}

@end

@implementation JYBaseInputView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _delegateList = [NSMapTable weakToStrongObjectsMapTable];
        lock = [[NSLock alloc] init];
        
        _textField = [[UITextField alloc] initWithFrame:frame];
        _textField.textAlignment = NSTextAlignmentLeft;
        _textField.delegate = self;
        _textField.font = [UIFont systemFontOfSize:15];
        [self addSubview:_textField];
                
        _textField.rightViewMode = UITextFieldViewModeAlways;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _textField.frame = CGRectMake(self.textEdgeInsets.left, self.textEdgeInsets.top,
                                  CGRectGetWidth(self.bounds) - self.textEdgeInsets.left - self.textEdgeInsets.right,
                                  CGRectGetHeight(self.bounds) - self.textEdgeInsets.top - self.textEdgeInsets.bottom);
}


#pragma mark - 对UITextField进行配置
- (void)setPlaceholder:(NSString *)placeholder {
    if (![_placeholder isEqualToString:placeholder]) {
        _placeholder = placeholder;
    }
    _textField.placeholder = placeholder;
}

- (void)setText:(NSString *)text {
    if (![_text isEqualToString:text]) {
        _text = text;
    }
    _textField.text = text;
}

- (void)setKeyboardType:(UIKeyboardType)keyboardType {
    if (_keyboardType != keyboardType) {
        _keyboardType = keyboardType;
    }
    _textField.keyboardType = keyboardType;
}

- (void)setClearButtonMode:(UITextFieldViewMode)clearButtonMode {
    _clearButtonMode = clearButtonMode;
    _textField.clearButtonMode = _clearButtonMode;
}

- (void)setClearsOnBeginEditing:(BOOL)clearsOnBeginEditing {
    _clearsOnBeginEditing = clearsOnBeginEditing;
    _textField.clearsOnBeginEditing = clearsOnBeginEditing;
}

- (void)setRightView:(UIView *)rightView {
    if (_rightView != rightView) {
        _rightView = rightView;
    }
    _textField.rightView = rightView;
}

- (void)setRegEx:(NSString *)regEx {
    if (regEx != _regEx) {
        _regEx = regEx;
    }
}

- (void)setContent:(id)content {
    if ([content isKindOfClass:[NSString class]]) {
        _textField.text = content;
    }
}

- (void)setTextEdgeInsets:(UIEdgeInsets)textEdgeInsets {
    _textEdgeInsets =textEdgeInsets;
    if (_textField) {
        CGRect frame = _textField.frame;
        frame.origin.x += textEdgeInsets.left;
        frame.origin.y += textEdgeInsets.top;
        frame.size.width -= (textEdgeInsets.left + textEdgeInsets.right);
        frame.size.height -= (textEdgeInsets.top + textEdgeInsets.bottom);
        _textField.frame = frame;
    }
}

- (void)setEditable:(BOOL)editable {
    _editable = editable;
    if (_textField) {
        _textField.enabled = editable;
        
        if (editable == NO) {
            _textField.textColor = [UIColor lightGrayColor];
        }
    }
}

#pragma mark - delegate
- (void)setDelegate:(id<JYAdaptorInputViewDelegate>)delegate {
    _delegate = delegate;
    
    [lock lock];
    NSInteger count = _delegateList.count;
    [lock unlock];
    
    // 在最前面插入一个
    for (NSInteger i = count; i > 0; i--) {
        NSString *desKey = [NSString stringWithFormat:@"%zi", i];
        NSString *orgKey = [NSString stringWithFormat:@"%zi", i - 1];
        id obj = [_delegateList objectForKey:orgKey];
        [_delegateList setObject:obj forKey:desKey];
    }
    
    [_delegateList setObject:_delegate forKey:@"0"];
}

- (void)addDelegate:(id<JYAdaptorInputViewDelegate>)delegate {
    NSAssert(delegate, @"delegate 不能为空");
    if (_delegateList
        && delegate
        && ![_delegateList.objectEnumerator.allObjects containsObject:delegate]) {
        
        [lock lock];
        NSInteger count = _delegateList.count;
        [lock unlock];
        
        NSString *newKey = [NSString stringWithFormat:@"%zi", count];
        [_delegateList setObject:delegate forKey:newKey];
    }
}

#pragma mark - <UITextFieldDelegate>
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    _textField = textField;
    
    NSArray <NSString *> *keyAry = [[_delegateList.keyEnumerator allObjects] sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull key1, NSString *  _Nonnull key2) {
        NSComparisonResult result  = [key1 compare:key2] * (-1);
        return result;
    }];
    
    [keyAry enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        id delegate = [_delegateList objectForKey:key];
        if ([delegate respondsToSelector:@selector(inputViewDidBeginInputView:)]) {
            [delegate inputViewDidBeginInputView:self];
        }
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField != _textField) return NO;

    NSArray <NSString *> *keyAry = [[_delegateList.keyEnumerator allObjects] sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull key1, NSString *  _Nonnull key2) {
        NSComparisonResult result  = [key1 compare:key2] * (-1);
        return result;
    }];
    
    // 代理优先
    id<JYAdaptorInputViewDelegate> delegateLast = [_delegateList objectForKey:keyAry.lastObject];
    // 仅_delegateList中的最后一个生效
    if ([delegateLast respondsToSelector:@selector(inputView:shouldChangeCharactersInRange:replacementString:)]) {
        return [delegateLast inputView:self shouldChangeCharactersInRange:range replacementString:string];
    }
    
    // 在返回前需要更新rightView的状态
    NSString *tmp = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    // 删除
    if ([@"" isEqualToString:string] || self.regEx == nil) {
        return YES;
    }
    
//    NSInteger maxLength = [JYVerifyRegEx contentSizeOfRegEx:self.regEx].height;
//    NSString *chart = [JYVerifyRegEx simpleChartVerifyRegEx:self.regEx];
//
//    BOOL lenghtVerify = tmp.length <= maxLength; // 仅校验长度
//    BOOL chartVerify = [JYVerifyRegEx verifyInputString:string regEx:chart]; // 仅输入的字符内容
//
//    // 校验时未超过最长，但会有不符要求的字符，所以需要同时满足
//    // 在校验不能为简单密码时，chartVerify截取错误
//    return self.regEx ? lenghtVerify && chartVerify : YES;
    
    return [JYVerifyRegEx verifyInputString:tmp regEx:self.regEx];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField == _textField) {
        
        NSArray <NSString *> *keyAry = [[_delegateList.keyEnumerator allObjects] sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull key1, NSString *  _Nonnull key2) {
            NSComparisonResult result  = [key1 compare:key2] * (-1);
            return result;
        }];
                
        [keyAry enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            id delegate = [_delegateList objectForKey:key];
            if ([delegate respondsToSelector:@selector(inputView:didFinishInput:)]) {
                [delegate inputView:self didFinishInput:textField.text];
            }
        }];
    }
}


@end
